package com.itheima.health.controller;

import com.itheima.health.common.MessageConst;
import com.itheima.health.entity.Result;
import com.itheima.health.pojo.User;
import com.itheima.health.service.MemberService;
import com.itheima.health.service.OrderService;
import com.itheima.health.service.ReportService;
import com.itheima.health.service.SetMealService;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 数据报告控制器
 */
@RestController
@RequestMapping("/report")
@Slf4j
public class ReportController {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private ReportService reportService;


    /**
     * 查询会员数量
     *
     * @return
     */
    @GetMapping("/getMemberReport")
    public Result getMemberReport() {
        //从redis中取出
        Map map = redisTemplate.opsForHash().entries("member");
        //判断
        if (map.get("months") == null) {
            Map<String, List<Object>> memberNumber = reportService.getSelectMember();
            //存入redis中
            redisTemplate.opsForHash().putAll("member", memberNumber);
            //在返回值给前端
            return new Result(true, MessageConst.ADD_SETMEAL_SUCCESS, memberNumber);
        }
        //可使用map返回或者实体类返回
        return new Result(true, MessageConst.ADD_SETMEAL_SUCCESS, map);
    }

    /**
     * 定时刷新
     * 每天10点
     */
    @Scheduled(cron = "0 0 10 * * ?")
    public void active() {
        //定时执行任务执行任务之前先将Redis中的旧数据删除
        redisTemplate.delete("member");
        //执行
        Map<String, List<Object>> memberNumber = reportService.getSelectMember();
        //存入redis中
        redisTemplate.opsForHash().putAll("member", memberNumber);
    }

    /**
     * 套餐占比图
     *
     * @return
     */
    @GetMapping("/getSetmealReport")
    public Result findAllSetmealReport() {

        //获取页面传输过来的数据 setmealCount套餐的数量和名字
        List<Map<String, Object>> list = reportService.findAll();
        //创建一个Map集合 存储套餐的名字和数量
        Map<String, Object> map = new HashMap<>();
        //添加套餐的名称和数量和名字
        map.put("setmealCount", list);
        //获取页面传输过来的数据 setmealNames 统计套餐的名称
        List<String> setmealNames = new ArrayList<>();
        //遍历list集合里的名字
        for (Map<String, Object> a : list) {
            //获取套餐的名字
            String name = (String) a.get("name");
            //添加名字到套餐名称中
            setmealNames.add(name);
        }
        map.put("setmealNames", setmealNames);
        return new Result(true, MessageConst.GET_SETMEAL_COUNT_REPORT_SUCCESS, map);
    }

    /**
     * 运营统计
     *
     * @return
     */
    @GetMapping("/getBusinessReportData")
    public Result getBusinessReportData() {

        Map<String, Object> map = reportService.getBusinessReportData();

        return new Result(true, MessageConst.GET_SETMEAL_COUNT_REPORT_SUCCESS, map);
    }

    /**
     * 导出excel
     *
     * @return
     */
    @GetMapping("/exportBusinessReport")
    public Result exportBusinessReport(HttpServletResponse response) throws IOException {
        Map<String, Object> data = reportService.getBusinessReportData();//excel表中数据

        InputStream in = this.getClass().getClassLoader().getResourceAsStream("report_template.xlsx");
        //获取工作簿
        XSSFWorkbook workbook = new XSSFWorkbook(in);
        //获取工作表
        XSSFSheet sheet = workbook.getSheet("sheet1");
        //显示日期的单元格为：第三行第六个单元格
        XSSFRow row = sheet.getRow(2);//获取第三行
        XSSFCell cell = row.getCell(5);//获取第六个单元格
        cell.setCellValue((String) data.get("reportDate"));//写出日期
        //写出今日新增会员，总会员
        row = sheet.getRow(4);
        row.getCell(5).setCellValue(String.valueOf(data.get("todayNewMember")));//今日新增会员
        row.getCell(7).setCellValue(String.valueOf(data.get("totalMember")));//总会员数
        //写出本周新增会员和本月新增会员
        row = sheet.getRow(5);
        row.getCell(5).setCellValue(String.valueOf(data.get("thisWeekNewMember")));//本周新增会员
        row.getCell(7).setCellValue(String.valueOf(data.get("thisMonthNewMember")));//本月新增会员
        //写出今日预约数和今日到诊数
        row = sheet.getRow(7);
        row.getCell(5).setCellValue(String.valueOf(data.get("todayOrderNumber")));//今日预约数
        row.getCell(7).setCellValue(String.valueOf(data.get("todayVisitsNumber")));//今日到诊数
        //写出本周预约数和本周到诊数
        row = sheet.getRow(8);
        row.getCell(5).setCellValue(String.valueOf(data.get("thisWeekOrderNumber")));//本周预约数
        row.getCell(7).setCellValue(String.valueOf(data.get("thisWeekVisitsNumber")));//本周到诊数
        //写出本月预约数和本月到诊数
        row = sheet.getRow(9);
        row.getCell(5).setCellValue(String.valueOf(data.get("thisMonthOrderNumber")));//本月预约数
        row.getCell(7).setCellValue(String.valueOf(data.get("thisMonthVisitsNumber")));//本月到诊数
        //写出热门套餐
        List<Map<String,Object>> hotSetmeals =(ArrayList)data.get("hotSetmeal");

        Map<String,Object> entry;
        for (int i = 0; i < hotSetmeals.size(); i++) {
            row =  sheet.getRow(12+i);
            entry = hotSetmeals.get(i);
            row.getCell(4).setCellValue((String)entry.get("name"));
            row.getCell(5).setCellValue((Long)entry.get("setmeal_count"));
            row.getCell(6).setCellValue((Double) entry.get("proportion"));
        }
        //将文件写出
        OutputStream out = response.getOutputStream();
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "inline; filename=excel.xls");
        workbook.write(out);
        out.flush();//清空缓冲区
        out.close();
        workbook.close();
        return new Result(true, MessageConst.ACTION_SUCCESS);
    }

//    @GetMapping("/getBusinessReportData")
//    public Result getBusinessReportData() {
//        Map<String, Object> map = new HashMap<>();
//        reportService.getBusinessReportData();
//        return new Result(true, MessageConst.GET_BUSINESS_REPORT_SUCCESS,map);
//    }
}
